package com.oa.co.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.github.pagehelper.PageInfo;
import com.oa.co.bo.PerformanceBo;
import com.oa.co.common.PageVo;
import com.oa.co.common.R;
import com.oa.co.listener.WebPerformanceListener;
import com.oa.co.pojo.Performance;
import com.oa.co.service.PerformanceService;
import com.oa.co.vo.PerformanceBarVo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin("*")
@RequestMapping("/api/performance")
public class PerformanceController {

    @Autowired
    private PerformanceService performanceService;

    @Autowired
    private WebPerformanceListener webPerformanceListener;

    /**
     * 查询所有的绩效
     * @param annual
     * @param quarter
     * @param page
     * @param limit
     * @return PageVo<Performance>
     */
    @RequestMapping("/performanceList")
    public PageVo<Performance> performanceList(String annual,String quarter,Integer page,Integer limit){

        PageVo<Performance> pageVo = new PageVo<>();
        PageInfo<Performance> pageData =  performanceService.selectPerformanceList(page,limit,annual,quarter);
        pageVo.setCode(0);

        pageVo.setCount(pageData.getTotal());
        pageVo.setData(pageData.getList());
        pageVo.setMsg("绩效分页数据");


        return pageVo;
    }

    /**
     * 删除绩效
     * @param id
     * @return
     */
    @RequestMapping("/delperformance")
    public R delPerformance(Integer id){
       int num = performanceService.delPerformance(id);
       if (num == 1){
           return R.ok().message("删除成功");
       }else {
           return R.error().message("删除失败");
       }
    }


    /**
     * 编辑绩效
     * @param performance
     * @return
     */
    @RequestMapping("/performanceEdit")
    public R performanceEdit(Performance performance){
        int num  = performanceService.performanceEdit(performance);
        if (num ==  1){
            return R.ok();
        }else {
            return R.error();
        }
    }

    /**
     * 添加绩效
     * @param performance
     * @return
     */
    @RequestMapping("/performanceAdd")
    public R performanceAdd(Performance performance){
       int num =  performanceService.performanceAdd(performance);
        if (num ==  1){
            return R.ok();
        }else {
            return R.error();
        }
    }

    /**
     * 年度绩效柱状图  饼图
     * @return
     */
    @RequestMapping("/bar")
    public R bar(){
        List<PerformanceBarVo> list = performanceService.performanceBarData();
        return R.ok().data("setBar",list);
    }

    /**
     * 导出表格数据
     * @param request
     * @param response
     * @param page
     * @param limit
     * @param annual
     * @param quarter
     * @throws IOException
     */
    //导出数据到excel 文件中
    @RequestMapping("/export")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, Integer page, Integer limit, String annual, String quarter) throws IOException {
        //下载 excel  模板文件
        //设置下载excel 的 响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");


        //防止中文乱码
        String filename = URLEncoder.encode("绩效信息导出", "utf-8");

        //告诉浏览器  你要下载文件
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");

        //得到一个 指向浏览器的输出流
        ServletOutputStream outputStream = response.getOutputStream();

        ExcelWriterBuilder write = EasyExcel.write(outputStream, PerformanceBo.class);

        ExcelWriterSheetBuilder sheet = write.sheet();

        //准备列表数据
        PageInfo<Performance> pageData = performanceService.selectPerformanceList(page,limit,annual,quarter);

        sheet.doWrite(pageData.getList());
    }

    /**
     * 下载模版
     * @param request
     * @param response
     * @throws IOException
     */
    //下载模板
    @RequestMapping("/downloadTemplate")
    public void templateDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //下载 excel  模板文件
        //设置下载excel 的 响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 得到这个文件的真实路径
        String realPath = request.getServletContext().getRealPath("/template.xlsx");;

        File file = new File(realPath);
        //借助 commons-io 的 工具类 把 file 对象转为 字节数组
        byte[] bytes = FileUtils.readFileToByteArray(file);

        //防止中文乱码
        String filename = URLEncoder.encode("年度绩效信息模板", "utf-8");

        //告诉浏览器  你要下载文件
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");

        //得到一个 指向浏览器的输出流
        ServletOutputStream outputStream = response.getOutputStream();

        //输出流 把字节数组 输出到 浏览器
        outputStream.write(bytes);
        //关闭流
        outputStream.close();

        //https://qq2078332610.oss-cn-beijing.aliyuncs.com/image/1683535970079.xlsx
        //在阿里云上直接下载文件到浏览器中
    }


    //import
    @RequestMapping("/import")
    @ResponseBody
    public R importFile(MultipartFile file){
        System.out.println("进入import");

        try {
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), PerformanceBo.class, webPerformanceListener);

            ExcelReaderSheetBuilder sheet = read.sheet();

            sheet.doRead();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    @RequestMapping("/delAllPerformance/{ids}")
    public R delAllPerformance(@PathVariable("ids") String ids){
        String substring = ids.substring(1, ids.length() - 1);
        String[] split = substring.split(",");
        List<Integer> list = new ArrayList<>();
        for (String s:split
             ) {
            int i = Integer.parseInt(s);
            list.add(i);
        }
        int num = performanceService.delAllPerformance(list);
        for (Integer i: list
             ) {
            System.out.println(i);
        }
        if(num != 0){
            return R.ok();
        }else {
            return R.error();
        }
    }

}
